package com.may.module.security.service.impl;

import com.may.module.security.entity.PermissionEntity;
import com.may.module.security.entity.UserEntity;
import com.may.module.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author May
 * @date 2021/08/03 17:15
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户
        UserEntity userEntity = userMapper.findByUsername(username);
        if (userEntity == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        // 查询权限
        List<PermissionEntity> permissionEntityList = userMapper.findPermissionByUsername(username);
        // 设置权限
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        permissionEntityList.forEach(p -> grantedAuthorities.add(new SimpleGrantedAuthority(p.getPermTag())));
        userEntity.setAuthorities(grantedAuthorities);
        return userEntity;
    }
}
